#include "Explosion.h"
#include "ParticleSystem.h"
#include "GameplayState.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include "../SGD Wrappers/SGD_MessageManager.h"
#include "../SGD Wrappers/SGD_AudioManager.h"
#include "MessageID.h"
#include "../SGD Wrappers/SGD_Message.h"
#include "Game.h"
#include "Camera.h"
#include "Player.h"
#include "StaticObject.h"


Explosion::Explosion()
{
	
	ParticleSystem ps;
	ps.Load("resource/savefiles/BOOM.xml", ps, *this);
	SetParticle(ps);
	ps.GetEmitter()->GetFlyweight()->AddRef();
	m_vtVelocity = {500,0};

	m_aAudio = SGD::AudioManager::GetInstance()->LoadAudio("resource/audio/Rumble.wav");
}


Explosion::~Explosion()
{

	SGD::AudioManager::GetInstance()->UnloadAudio(m_aAudio);

	for (unsigned int j = 0; j < m_vtParticle.size(); j++)
	{
		m_vtParticle[j]->GetEmitter()->GetAliveVec().clear();

		while (m_vtParticle[j]->GetEmitter()->GetFlyweight()->GetRefCount() > 1)
			m_vtParticle[j]->GetEmitter()->GetFlyweight()->Release();

		delete m_vtParticle[j];
	}
	m_vtParticle.clear();
	
}


void Explosion::Update(float dt)
{
	if (m_bAlive || m_ptPosition.x <= 20160)
	{
		GameplayState* pGame = GameplayState::GetInstance();
		m_ptPosition.y = pGame->GetPlayerPos().y - 300;
		m_vtParticle[0]->GetEmitter()->Update(dt);

		if (!SGD::AudioManager::GetInstance()->IsAudioPlaying(m_aAudio))
			SGD::AudioManager::GetInstance()->PlayAudio(m_aAudio);

		if (pGame->GetWorldTimer() <= 0)
		{
			m_vtParticle[0]->Update(dt);
			m_ptPosition.x += (m_vtVelocity.x *dt);
		}
	}
	else
	{
		if (SGD::AudioManager::GetInstance()->IsAudioPlaying(m_aAudio))
			SGD::AudioManager::GetInstance()->StopAudio(m_aAudio);
	}

}

void Explosion::Render()
{
	if (m_bAlive)
	{
		SGD::GraphicsManager * graphics = SGD::GraphicsManager::GetInstance();
		m_vtParticle[0]->Render();
	}
}

void Explosion::HandleCollision(BaseObject* pOther)
{
	if (dynamic_cast<Player*>(pOther))
	{
		pOther->SetAlive(false);
	}

	if (dynamic_cast<StaticObject*>(pOther))
	{
		if (dynamic_cast<StaticObject*>(pOther)->GetObjectType() == ObjectType::Safe)
		{
			pOther->SetAlive(false);
		}
	}
}

void Explosion::Reset()
{
	for (unsigned int j = 0; j < m_vtParticle.size(); j++)
	{
		m_vtParticle[j]->GetEmitter()->GetAliveVec().clear();

		while (m_vtParticle[j]->GetEmitter()->GetFlyweight()->GetRefCount() > 1)
			m_vtParticle[j]->GetEmitter()->GetFlyweight()->Release();

		delete m_vtParticle[j];
	}
	m_vtParticle.clear();

	ParticleSystem ps;
	ps.Load("resource/savefiles/BOOM.xml", ps, *this);
	SetParticle(ps);
	ps.GetEmitter()->GetFlyweight()->AddRef();
	m_vtVelocity = { 500, 0 };
}